import dayjs from 'dayjs'

import { axiosMock, delayFn, randArrItem } from '@/services/axiosMock'
import {
  IAddNoteReq,
  ICargoCommentInfo,
  IFirstLegInformationRes,
  IGetBoxNumberMapInformationReq,
  IGetDetailReq,
  IGetNoteReq,
  IOrderProductBoxInfoRes,
  ISetFirstLegInformationReq,
  ISetLastLegInformationReq,
  ISetLogisticsChannelReq,
  ISetLogisticsProductReq,
  ISetTransferWarehouseReq,
  IUploadWaybillAttach,
  IWarehouseListRes,
  IWaybillAttachDetailRes,
  IWaybillDetailRes,
  IWaybillPublishPathRes,
  IWaybillTransferWarehouseInformationRes,
  StaffV2ODTO,
  User,
} from '../interface'

// 生成随机但稳定的数据（按运单号缓存）
const CACHE = new Map<string, IWaybillDetailRes>()
const FIRST_LEG_CACHE = new Map<string, IFirstLegInformationRes>()
const NOTES_CACHE = new Map<string, IGetNoteReq[]>()

const fmt = (ts: number) => new Date(ts).toISOString()
const now = Date.now()

// 格式化为 YYYY-MM-DD（兼容字符串、Date、Dayjs）
const fmtYMD = (input?: any): string | undefined => {
  if (input == null) return undefined
  return dayjs(input).format('YYYY-MM-DD')
}

const randomUser = (id: number): User => {
  const names = ['张三', '李四', '王五', '赵六', '陈七'] as const
  const en = ['Alice', 'Bob', 'Carol', 'David', 'Eva'] as const
  return {
    id,
    active: true,
    name: names[id % names.length],
    englishName: en[id % en.length],
    username: `u${id}`,
    phone: `138${String(10000000 + id).slice(-8)}`,
    departmentId: 100 + id,
    roleId: 10 + (id % 5),
  }
}

const randomStaffList = (): StaffV2ODTO[] => {
  return [1, 2, 3, 4, 5].map(t => ({ staffType: t, user: randomUser(100 + t) }))
}

const createDetail = (waybillNo: string): IWaybillDetailRes => {
  const base = 24 * 60 * 60 * 1000
  const t1 = now - base * randArrItem([1, 2, 3, 4, 5])
  const t2 = now - base * randArrItem([1, 2, 3])

  const logisticsTransport = randArrItem([1, 2, 3, 4])
  const productTransport = randArrItem([1, 2, 3, 4])
  const lastMileTransport = randArrItem([1, 2, 3])

  const serviceLevel = randArrItem([1, 2, 3])
  const serviceMin = randArrItem([3, 5, 7])
  const serviceMax = randArrItem([10, 12, 15])

  const statusMain = randArrItem([11, 12, 13, 14, 15, 16, 17, 18, 19])

  return {
    waybillNo,
    logisticsProductInlineName: `LP${String(Math.floor(Math.random() * 10000)).padStart(4, '0')}`,
    logisticsProductName: randArrItem(['FBA Standard', 'FBA Fast', 'FBA Expedited']),
    logisticsProductTransportType: productTransport,
    logisticsProductServiceLevel: serviceLevel,
    logisticsProductServiceTransitMin: serviceMin,
    logisticsProductServiceTransitMax: serviceMax,

    logisticsChannelCode: `LC${String(Math.floor(Math.random() * 10000)).padStart(4, '0')}`,
    logisticsChannelName: randArrItem(['Amazon Freight', 'UPS', 'FedEx', 'DHL']) || 'DHL',
    logisticsChannelTransportType: logisticsTransport,
    logisticsChannelServiceLevel: serviceLevel,
    logisticsChannelServiceTransitMin: serviceMin,
    logisticsChannelServiceTransitMax: serviceMax,
    logisticsChannelMerchantServers: randArrItem(['上海分部', '深圳分部', '美国分部', '德国分部']),
    logisticsChannelTrackingNumber: `TR${Math.floor(Math.random() * 10 ** 8)}`,

    lastMileCarrier: randArrItem(['Amazon', 'UPS', 'USPS', 'FedEx']),
    lastMileTransportType: lastMileTransport,
    lastMileWaybillNo: `LM${Math.floor(Math.random() * 10 ** 8)}`,

    edd: fmtYMD(t2 + base * randArrItem([1, 2, 3])),
    deliveryTime: fmt(t2 + base * randArrItem([1, 2, 3])),
    scheduledDeliveryTime: randArrItem(['AM', 'PM', 'ANY']),
    scheduledDeliveryTimeSlot: randArrItem(['8:00-12:00', '13:00-18:00', '18:00-20:00']),
    shipmentDate: fmtYMD(t1),
    signingTime: fmtYMD(t2),
    consolidationWarehouseId: Math.floor(Math.random() * 1000),
    transitWarehouseId: Math.floor(Math.random() * 1000),

    waybillStatus: statusMain,
    waybillStatusUpdateTime: { [String(statusMain)]: fmt(now - base * randArrItem([1, 2])) },

    staffInfoList: randomStaffList(),

    createAt: fmt(t1 - base),
    createBy: 'system',
    updateBy: randArrItem(['Alice', 'Bob', 'Carol']) || 'Alice',
    updateAt: fmt(now),
  }
}

const createFirstLegInfo = (waybillNo: string): IFirstLegInformationRes => {
  const transportType = randArrItem([1, 2, 3, 4])
  const etd = fmtYMD(now - 24 * 60 * 60 * 1000 * randArrItem([1, 2, 3]))!
  const eta = fmtYMD(now + 24 * 60 * 60 * 1000 * randArrItem([2, 3, 4]))!
  const carriers = ['COSCO', 'Maersk', 'Delta', 'UPS', 'DHL', 'CMA CGM'] as const
  const cities = ['Shanghai', 'Shenzhen', 'Los Angeles', 'Seattle', 'Hamburg', 'Rotterdam'] as const

  return {
    transportType,
    carrier: randArrItem(carriers),
    departureLocation: randArrItem(cities),
    destinationLocation: randArrItem(cities),
    etd,
    eta,
    // AIR 场景生成航班号（2）
    flightNumber: transportType === 2 ? `DL${Math.floor(Math.random() * 9000 + 1000)}` : undefined,
    // OCEAN 场景生成船名/柜号/航次（1）
    vesselName: transportType === 1 ? randArrItem(['Evergreen', 'OOCL Berlin', 'MSC Zoe']) : undefined,
    containerNumber: transportType === 1 ? `CONT${Math.floor(Math.random() * 10 ** 6)}` : undefined,
    trainTruckNumber:
      transportType === 3 || transportType === 4 ? `TT${Math.floor(Math.random() * 10 ** 6)}` : undefined,
    voyageNumber: transportType === 1 ? `VOY${Math.floor(Math.random() * 900 + 100)}` : undefined,
  }
}

axiosMock('default', mock => {
  // 获取运单详情
  mock.onPost(`/tmsapi/waybill_record_v2/waybill_detail`).reply(
    delayFn<IWaybillDetailRes>(600, ({ data }) => {
      const waybillNo = String(data?.waybillNo || '')
      if (!waybillNo) {
        return { success: false, message: '缺少参数 waybillNo' } as any
      }
      if (!CACHE.has(waybillNo)) CACHE.set(waybillNo, createDetail(waybillNo))
      return { success: true, data: CACHE.get(waybillNo)! }
    }),
  )

  // 设置物流产品
  mock.onPost(`/tmsapi/waybill_record_v2/set/logistics_product`).reply(
    delayFn<IWaybillDetailRes>(500, ({ data }) => {
      const req = (data || {}) as ISetLogisticsProductReq
      const waybillNo = String(req?.waybillNo || '')
      if (!waybillNo) return { success: false, message: '缺少参数 waybillNo' } as any
      if (!CACHE.has(waybillNo)) CACHE.set(waybillNo, createDetail(waybillNo))
      const detail = { ...CACHE.get(waybillNo)! }

      detail.logisticsProductTransportType = req.logisticsProductTransportType ?? detail.logisticsProductTransportType
      detail.logisticsProductServiceLevel = req.logisticsProductServiceLevel ?? detail.logisticsProductServiceLevel
      detail.logisticsProductServiceTransitMin =
        req.logisticsProductServiceTransitMin ?? detail.logisticsProductServiceTransitMin
      detail.logisticsProductServiceTransitMax =
        req.logisticsProductServiceTransitMax ?? detail.logisticsProductServiceTransitMax

      detail.updateBy = 'mock'
      detail.updateAt = fmt(now)
      CACHE.set(waybillNo, detail)
      return { success: true, data: detail }
    }),
  )

  // 设置物流渠道
  mock.onPost(`/tmsapi/waybill_record_v2/set/logistics_channel`).reply(
    delayFn<IWaybillDetailRes>(500, ({ data }) => {
      const req = (data || {}) as ISetLogisticsChannelReq
      const waybillNo = String(req?.waybillNo || '')
      if (!waybillNo) return { success: false, message: '缺少参数 waybillNo' } as any
      if (!CACHE.has(waybillNo)) CACHE.set(waybillNo, createDetail(waybillNo))
      const detail = { ...CACHE.get(waybillNo)! }

      detail.logisticsChannelTransportType = req.logisticsChannelTransportType ?? detail.logisticsChannelTransportType
      detail.logisticsChannelServiceLevel = req.logisticsChannelServiceLevel ?? detail.logisticsChannelServiceLevel
      detail.logisticsChannelServiceTransitMin =
        req.logisticsChannelServiceTransitMin ?? detail.logisticsChannelServiceTransitMin
      detail.logisticsChannelServiceTransitMax =
        req.logisticsChannelServiceTransitMax ?? detail.logisticsChannelServiceTransitMax
      detail.logisticsChannelMerchantServers =
        req.logisticsChannelMerchantServers ?? detail.logisticsChannelMerchantServers
      detail.logisticsChannelTrackingNumber =
        req.logisticsChannelTrackingNumber ?? detail.logisticsChannelTrackingNumber

      detail.updateBy = 'mock'
      detail.updateAt = fmt(now)
      CACHE.set(waybillNo, detail)
      return { success: true, data: detail }
    }),
  )

  // 获取头程信息
  mock.onPost(`/tmsapi/waybill_record_v2/waybill_first_leg_information`).reply(
    delayFn<IFirstLegInformationRes>(400, ({ data }) => {
      const req = (data || {}) as IGetDetailReq
      const waybillNo = String(req?.waybillNo || '')
      if (!waybillNo) return { success: false, message: '缺少参数 waybillNo' } as any
      if (!FIRST_LEG_CACHE.has(waybillNo)) FIRST_LEG_CACHE.set(waybillNo, createFirstLegInfo(waybillNo))
      return { success: true, data: FIRST_LEG_CACHE.get(waybillNo)! }
    }),
  )

  // 设置头程信息（回写部分到 IWaybillDetailRes 以便界面刷新）
  mock.onPost(`/tmsapi/waybill_record_v2/set/first_leg_information`).reply(
    delayFn<IWaybillDetailRes>(500, ({ data }) => {
      const req = (data || {}) as ISetFirstLegInformationReq
      const waybillNo = String(req?.waybillNo || '')
      if (!waybillNo) return { success: false, message: '缺少参数 waybillNo' } as any
      if (!CACHE.has(waybillNo)) CACHE.set(waybillNo, createDetail(waybillNo))
      const detail = { ...CACHE.get(waybillNo)! }

      // 同步缓存的头程信息
      FIRST_LEG_CACHE.set(waybillNo, {
        transportType: req.transportType,
        carrier: req.carrier,
        departureLocation: req.departureLocation,
        destinationLocation: req.destinationLocation,
        etd: fmtYMD(req.etd),
        eta: fmtYMD(req.eta),
        flightNumber: req.flightNumber,
        vesselName: req.vesselName,
        containerNumber: req.containerNumber,
        trainTruckNumber: req.trainTruckNumber,
        voyageNumber: req.voyageNumber,
      })

      // 回写关键字段到运单详情，便于查看态展示
      detail.shipmentDate = fmtYMD(req.etd) ?? detail.shipmentDate
      detail.edd = fmtYMD(req.eta) ?? detail.edd

      detail.updateBy = 'mock'
      detail.updateAt = fmt(now)
      CACHE.set(waybillNo, detail)
      return { success: true, data: detail }
    }),
  )

  // 设置尾程信息
  mock.onPost(`/tmsapi/waybill_record_v2/set/last_leg_information`).reply(
    delayFn<IWaybillDetailRes>(500, ({ data }) => {
      const req = (data || {}) as ISetLastLegInformationReq
      const waybillNo = String(req?.waybillNo || '')
      if (!waybillNo) return { success: false, message: '缺少参数 waybillNo' } as any
      if (!CACHE.has(waybillNo)) CACHE.set(waybillNo, createDetail(waybillNo))
      const detail = { ...CACHE.get(waybillNo)! }

      detail.lastMileCarrier = req.lastMileCarrier ?? detail.lastMileCarrier
      detail.lastMileTransportType = req.lastMileTransportType ?? detail.lastMileTransportType
      detail.lastMileWaybillNo = req.lastMileWaybillNo ?? detail.lastMileWaybillNo

      detail.updateBy = 'mock'
      detail.updateAt = fmt(now)
      CACHE.set(waybillNo, detail)
      return { success: true, data: detail }
    }),
  )

  // 获取运单发布路径
  mock.onPost(`/tmsapi/waybill_record_v2/waybill_publish_path`).reply(
    delayFn<IWaybillPublishPathRes[]>(400, ({ data }) => {
      const req = (data || {}) as IGetDetailReq
      const waybillNo = String(req?.waybillNo || '')
      if (!waybillNo) return { success: false, message: '缺少参数 waybillNo' } as any
      const base = 24 * 60 * 60 * 1000
      const entries: IWaybillPublishPathRes[] = [1, 2, 3].map((i, idx) => ({
        eventTime: fmt(now - base * (4 - idx)),
        locationType: randArrItem([1, 2, 3, 4, 5, 6]),
        messageType: randArrItem([1, 2, 3]),
        note: randArrItem(['创建运单', '离港', '到港', '清关完成', '派送中', '已签收']),
        publishId: Math.floor(Math.random() * 100000),
        shipTrackStatus: randArrItem([1, 2, 3]),
        syncAt: fmt(now - base * (3 - idx)),
        updateAt: fmt(now - base * (3 - idx)),
        templateCn: '模板中文描述',
        templateEn: 'Template English',
        updateBy: randArrItem(['Alice', 'Bob', 'Carol']),
        visibleFlag: randArrItem([0, 1]),
      }))
      return { success: true, data: entries }
    }),
  )

  // 获取运单中转仓信息
  mock.onPost(`/tmsapi/waybill_record_v2/waybill_transfer_warehouse_information`).reply(
    delayFn<IWaybillTransferWarehouseInformationRes>(400, ({ data }) => {
      const req = (data || {}) as IGetDetailReq
      const waybillNo = String(req?.waybillNo || '')
      if (!waybillNo) return { success: false, message: '缺少参数 waybillNo' } as any
      const warehouses = [
        {
          address: '上海市浦东新区XX路100号',
          email: 'wh1@example.com',
          person: '张三',
          phone: '021-12345678',
          warehouseId: 'W100',
          warehouseName: '上海中转仓',
          warehouseType: 1,
        },
        {
          address: '深圳市南山区YY路88号',
          email: 'wh2@example.com',
          person: '李四',
          phone: '0755-87654321',
          warehouseId: 'W200',
          warehouseName: '深圳中转仓',
          warehouseType: 2,
        },
      ]
      return { success: true, data: { warehouseODTOS: warehouses } }
    }),
  )

  // 获取运单附件详情
  mock.onPost(`/tmsapi/waybill_record_v2/waybill_attach_detail`).reply(
    delayFn<IWaybillAttachDetailRes>(400, ({ data }) => {
      const req = (data || {}) as IGetDetailReq
      const waybillNo = String(req?.waybillNo || '')
      if (!waybillNo) return { success: false, message: '缺少参数 waybillNo' } as any
      const res: IWaybillAttachDetailRes = {
        fileName: `attach_${waybillNo}.pdf`,
        fileType: randArrItem([1, 2]),
        fileUrl: `https://example.com/${waybillNo}/attach.pdf`,
        comment: '这是一个测试附件',
        createAt: fmt(now),
      }
      return { success: true, data: res }
    }),
  )

  // 上传运单附件
  mock.onPost(`/tmsapi/waybill_record_v2/uploadWaybillAttach`).reply(
    delayFn<IUploadWaybillAttach>(600, () => {
      const params = [
        {
          fileName: `new_upload_${Math.floor(Math.random() * 1000)}.pdf`,
          fileType: 1,
          fileUrl: `https://example.com/uploads/${Math.floor(Math.random() * 100000)}.pdf`,
          waybillNo: `WB${Math.floor(Math.random() * 100000)}`,
        },
      ]
      return { success: true, data: { attachListParams: params } }
    }),
  )

  // 设置集货仓/中转仓
  mock.onPost(`/tmsapi/waybill_record_v2/set/warehouse`).reply(
    delayFn<IWaybillDetailRes>(500, ({ data }) => {
      const req = (data || {}) as ISetTransferWarehouseReq
      const waybillNo = String(req?.waybillNo || '')
      if (!waybillNo) return { success: false, message: '缺少参数 waybillNo' } as any
      if (!CACHE.has(waybillNo)) CACHE.set(waybillNo, createDetail(waybillNo))
      const detail = { ...CACHE.get(waybillNo)! }
      if (req.warehouseType === 1) {
        detail.consolidationWarehouseId = Number(req.warehouseId ?? detail.consolidationWarehouseId)
      } else if (req.warehouseType === 2) {
        detail.transitWarehouseId = Number(req.warehouseId ?? detail.transitWarehouseId)
      }
      detail.updateBy = 'mock'
      detail.updateAt = fmt(now)
      CACHE.set(waybillNo, detail)
      return { success: true, data: detail }
    }),
  )

  // 添加备注（统一到新接口）
  mock.onPost(`/tmsapi/waybill_record_v2/set/note`).reply(
    delayFn<IWaybillDetailRes>(300, ({ data }) => {
      const req = (data || {}) as IAddNoteReq
      const waybillNo = String(req?.waybillNo || '')
      if (!waybillNo) return { success: false, message: '缺少参数 waybillNo' } as any
      const list = NOTES_CACHE.get(waybillNo) ?? []
      const entry: IGetNoteReq = { createAt: fmt(now), note: req.note ?? '', user: randomUser(1) }
      NOTES_CACHE.set(waybillNo, [entry, ...list])
      // 同步更新 detail 的 updateAt/updateBy
      if (!CACHE.has(waybillNo)) CACHE.set(waybillNo, createDetail(waybillNo))
      const detail = { ...CACHE.get(waybillNo)! }
      detail.updateBy = 'mock'
      detail.updateAt = fmt(now)
      if (req.fileUrl) entry.fileUrl = req.fileUrl
      CACHE.set(waybillNo, detail)
      return { success: true, data: detail }
    }),
  )

  // 获取备注列表
  mock.onPost(`/tmsapi/waybill_record_v2/get/note`).reply(
    delayFn<IGetNoteReq[]>(300, ({ data }) => {
      const req = (data || {}) as IGetDetailReq
      const waybillNo = String(req?.waybillNo || '')
      if (!waybillNo) return { success: false, message: '缺少参数 waybillNo' } as any
      if (!NOTES_CACHE.has(waybillNo)) {
        NOTES_CACHE.set(waybillNo, [{ createAt: fmt(now - 3600_000), note: '系统初始化备注', user: randomUser(2) }])
      }
      return { success: true, data: NOTES_CACHE.get(waybillNo)! }
    }),
  )

  // 获取运单箱号映射信息
  mock.onPost(`/tmsapi/waybill_record_v2/box_number_map_information`).reply(
    delayFn<IGetBoxNumberMapInformationReq[]>(400, ({ data }) => {
      const req = (data || {}) as IGetDetailReq
      const waybillNo = String(req?.waybillNo || '')
      if (!waybillNo) return { success: false, message: '缺少参数 waybillNo' } as any
      const rows: IGetBoxNumberMapInformationReq[] = [1, 2, 3].map(i => ({
        carrier: randArrItem(['UPS', 'FedEx', 'DHL']),
        fbaBoxNumber: `FBA${waybillNo}-${i}`,
        latestRouting: randArrItem(['SH→LA', 'SZ→SEA', 'HAM→RTM']),
        masterWaybillNo: `MAWB${Math.floor(Math.random() * 10 ** 6)}`,
        trackingNumber: `TR${Math.floor(Math.random() * 10 ** 8)}`,
      }))
      return { success: true, data: rows }
    }),
  )

  // 导入运单箱号映射信息
  mock.onPost(`/tmsapi/waybill_record_v2/box_number_map/import`).reply(
    delayFn<IWaybillDetailRes>(500, ({ data }) => {
      const req = (data || {}) as { file: string }
      // 仅接收 file，与 index.ts 签名保持一致；返回一个稳定的运单详情用于刷新界面。
      const cachedFirst = Array.from(CACHE.keys())[0]
      const waybillNo = cachedFirst || `WB${Math.floor(Math.random() * 100000)}`
      if (!CACHE.has(waybillNo)) CACHE.set(waybillNo, createDetail(waybillNo))
      const detail = { ...CACHE.get(waybillNo)! }
      detail.updateBy = 'mock'
      detail.updateAt = fmt(now)
      CACHE.set(waybillNo, detail)
      return { success: true, data: detail }
    }),
  )

  // 获取中转仓列表
  mock.onPost(`/tmsapi/waybill_record_v2/warehouse/list`).reply(
    delayFn<IWarehouseListRes[]>(400, () => {
      const list: IWarehouseListRes[] = [
        {
          address: '上海市青浦区Z仓',
          email: 'wh_sh@example.com',
          person: '王五',
          phone: '021-99999999',
          warehouseId: 'W300',
          warehouseName: '上海仓',
          warehouseType: 1,
        },
        {
          address: '洛杉矶A仓',
          email: 'wh_la@example.com',
          person: 'Mike',
          phone: '001-22223333',
          warehouseId: 'W400',
          warehouseName: 'LA仓',
          warehouseType: 2,
        },
      ]
      return { success: true, data: list }
    }),
  )

  // 设置是否为ISA/BL
  mock.onPost(`/tmsapi/waybill_record_v2/set/isa_bl`).reply(
    delayFn<IWaybillDetailRes>(400, ({ data }) => {
      const req = (data || {}) as { bl?: string; isa?: string; waybillNo?: string }
      const waybillNo = String(req?.waybillNo || '')
      if (!waybillNo) return { success: false, message: '缺少参数 waybillNo' } as any
      if (!CACHE.has(waybillNo)) CACHE.set(waybillNo, createDetail(waybillNo))
      const detail = { ...CACHE.get(waybillNo)! }
      if (typeof req.bl !== 'undefined') detail.bl = req.bl || undefined
      if (typeof req.isa !== 'undefined') detail.isa = req.isa || undefined
      detail.updateBy = 'mock'
      detail.updateAt = fmt(now)
      CACHE.set(waybillNo, detail)
      return { success: true, data: detail }
    }),
  )

  // 运单状态总览
  mock.onPost(`/tmsapi/waybill_record_v2/waybill_status_overview`).reply(
    delayFn<{
      statusODTOList: { scheduledDeliveryTimeSlot?: string; status?: number; statusGroup?: number; updateAt?: string }[]
    }>(400, ({ data }) => {
      const req = (data || {}) as IGetDetailReq
      const waybillNo = String(req?.waybillNo || '')
      if (!waybillNo) return { success: false, message: '缺少参数 waybillNo' } as any
      const base = 24 * 60 * 60 * 1000
      const nowTs = now
      const mk = (status: number, statusGroup: number, hasSlot = false) => ({
        status,
        statusGroup,
        updateAt: fmt(nowTs - base * randArrItem([1, 2, 3, 4])),
        scheduledDeliveryTimeSlot: hasSlot ? randArrItem(['8:00-12:00', '13:00-18:00', '18:00-20:00']) : undefined,
      })
      const list = [
        // 主状态 11-19
        mk(randArrItem([11, 12, 13, 14, 15, 16, 17, 18, 19]), 1),
        // 报关 21-27
        mk(randArrItem([21, 22, 23, 24, 25, 26, 27]), 2),
        // 清关 31-38
        mk(randArrItem([31, 32, 33, 34, 35, 36, 37, 38]), 3),
        // 预约 41-48（含送达时段）
        mk(randArrItem([41, 42, 43, 44, 45, 46, 47, 48]), 4, true),
        // 保险 51-55
        mk(randArrItem([51, 52, 53, 54, 55]), 5),
        // 异常 61-66
        mk(randArrItem([61, 62, 63, 64, 65, 66]), 6),
      ]
      return { success: true, data: { statusODTOList: list } }
    }),
  )

  // 获取订单产品箱信息统计
  mock.onPost(`/tmsapi/waybill_record_v2/getOrderProductBoxInfo`).reply(
    delayFn<IOrderProductBoxInfoRes>(400, ({ data }) => {
      const req = (data || {}) as IGetDetailReq
      const waybillNo = String(req?.waybillNo || '')
      const seed = waybillNo ? waybillNo.length : Math.floor(Math.random() * 10)
      const boxNum = 3 + (seed % 5)
      const weight = (100 + (seed % 50)).toFixed(1)
      const volume = (10 + (seed % 10)).toFixed(2)
      const res: IOrderProductBoxInfoRes = {
        boxNum,
        weight: `${weight}kg`,
        volume: `${volume}m³`,
      }
      return { success: true, data: res }
    }),
  )
  // 添加备注
  mock.onPost(`/fba_otb/cargo/addComment`).reply(
    delayFn<void>(300, ({ data }) => {
      const req = (data || {}) as ICargoCommentInfo
      if (!req?.cargoNo) return { success: false, message: '缺少参数 cargoNo' } as any
      // 备注写入模拟：实际不存储，仅返回成功
      return { success: true, data: undefined as unknown as void }
    }),
  )
})
